package com.gmics.unifiq.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gmics.unifiq.ComparisonResultActivity;
import com.gmics.unifiq.controller.JSONParser;
import com.gmics.android.R;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class CompareCoursesFragment extends Fragment {
	
	
	Spinner sp2;
	Spinner sp1;
	AutoCompleteTextView ac2, ac1;
	//CustomAutoCompleteTextView ac1;
	TextView tv1;
	Button btnCompare;
	EditText addressEt;
	CheckBox useCurLocCb;
	
	ArrayAdapter<String> spAdapter1, spAdapter2, acAdapter1, acAdapter2;
	List<String> uniArray, courseArray, tempArray, tempArray1, ntuArray, nusArray, smuArray, sitArray;
	int pos;
	
	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();

	ArrayList<HashMap<String, String>> uniList;

	// url to get all products list
	private static String url_all_universities = "http://unifiq.5kportal.com/comparison_api1/get_all_universities.php";
	private static String url_all_courses = "http://unifiq.5kportal.com/comparison_api1/get_all_courses.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_UNIVERSITIES = "universities"; 
	private static final String TAG_UID = "uniId";
	private static final String TAG_UNINAME = "uniName";
	
	private static final String TAG_COURSES = "courses";
	private static final String TAG_COURSENAME = "courseName";
	
	Editable selected1 = null;
	Editable selected2 = null;

	// products JSONArray
	JSONArray universities = null;
	JSONArray courses = null;

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.select_comparison, container,
				false);
		
		sp1 = (Spinner) rootView.findViewById(R.id.spinner1);
		ac1 = (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteTextView1);
		sp2 = (Spinner) rootView.findViewById(R.id.spinner2);
		ac2 = (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteTextView2);
		addressEt = (EditText) rootView.findViewById(R.id.address_tv);
		useCurLocCb = (CheckBox) rootView.findViewById(R.id.useCurLocCb);
		
		// Hashmap for ListView
		uniList = new ArrayList<HashMap<String, String>>();

		// Loading products in Background Thread
		new LoadAllUniAndCourses().execute();
		
		
		useCurLocCb.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean checked) {
				// TODO Auto-generated method stub
				if (checked==true)
				{
					addressEt.setEnabled(false);
				}
				else
				{
					addressEt.setEnabled(true);
				}
			}
			
		});
		
		
		sp1.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int pos, long arg3) {
				// TODO Auto-generated method stub
				ac1.setText("");
				
				String a = (String) sp1.getItemAtPosition(pos);
				Log.d("Item Selected", a);
				
				if(a.equals("All"))
				{
					acAdapter1 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, tempArray);
				}
				else if(a.equals("NUS"))
				{
					acAdapter1 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, nusArray);
				}
				else if(a.equals("SMU"))
				{
					acAdapter1 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, smuArray);
				}
				else if(a.equals("NTU"))
				{
					acAdapter1 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, ntuArray);
				}
				else if(a.equals("SIT"))
				{
					acAdapter1 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, sitArray);
				}
				ac1.setAdapter(acAdapter1);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		
		sp2.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int pos, long arg3) {
				// TODO Auto-generated method stub
				ac2.setText("");
				
				String a = (String) sp2.getItemAtPosition(pos);
				Log.d("Item Selected", a);
				
				if(a.equals("All"))
				{
					acAdapter2 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, tempArray);
				}
				else if(a.equals("NUS"))
				{
					acAdapter2 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, nusArray);
				}
				else if(a.equals("SMU"))
				{
					acAdapter2 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, smuArray);
				}
				else if(a.equals("NTU"))
				{
					acAdapter2 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, ntuArray);
				}
				else if(a.equals("SIT"))
				{
					acAdapter2 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, sitArray);
				}
				ac2.setAdapter(acAdapter2);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		
		ac1.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				// TODO Auto-generated method stub
				
				selected1 = ac1.getText();
				
				if(selected1.equals(selected2))
				{
					ac1.setText("");
				}			
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		ac2.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				
				selected2 = ac2.getText();
				
				if(selected1.equals(selected2))
				{
					ac2.setText("");
				}	
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		ac1.setOnTouchListener(new View.OnTouchListener(){
			   @Override
			   public boolean onTouch(View v, MotionEvent event){
			      ac1.showDropDown();
			      return false;
			   }
		});
		
		ac2.setOnTouchListener(new View.OnTouchListener(){
			   @Override
			   public boolean onTouch(View v, MotionEvent event){
			      ac2.showDropDown();
			      return false;
			   }
		});
		
		
		btnCompare = (Button) rootView.findViewById(R.id.btnCompare);
		//final Context context = getActivity();
		btnCompare.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				Log.d("ac1", ac1.getText().toString());
				Log.d("ac2", ac2.getText().toString());
				
				if(ac1.getText().toString().equals("") || ac2.getText().toString().equals(""))
				{
					Toast.makeText(getActivity(), 
                            "Please select 2 courses", Toast.LENGTH_LONG).show();
				}
				else if(ac1.getText().toString().equals(ac2.getText().toString()))
				{
					Toast.makeText(getActivity(), 
                            "Please choose 2 different courses", Toast.LENGTH_LONG).show();
				}
				else
				{
					
    				Intent update = new Intent(getActivity(), ComparisonResultActivity.class);
    	        	//update.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    				Bundle b = new Bundle();
    				b.putString("courseName", ac1.getText().toString());
    				b.putString("courseName1", ac2.getText().toString());
    				
    				if (addressEt.isEnabled()==false)
					{
    					b.putString("address", "usecurrentlocation");
					}
    				else
    				{
    					b.putString("address", addressEt.getText().toString());
    				}
    				
    				update.putExtras(b);
    	        	startActivity(update);
    	        	
    	        	// Closing dashboard screen
    	        	//finish();	

				}
				
			}
			
		});
		
		return rootView;
	}
	
	class LoadAllUniAndCourses extends AsyncTask<String, String, String> 
	{

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Loading Universities and Courses. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		protected String doInBackground(String... args) {
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			
			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(url_all_universities, "GET", params);

			// Check your log cat for JSON reponse
			Log.d("All University: ", json.toString());
			
			// University spinner data
			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);
				
				if (success == 1) 
				{
					// products found
					// Getting Array of Products
					
					universities = json.getJSONArray(TAG_UNIVERSITIES);
						
					uniArray = new ArrayList<String>();
					
					uniArray.add("All");
					
					// looping through All Products
					for (int i = 0; i < universities.length(); i++) 
					{
						JSONObject c = universities.getJSONObject(i);

						// Storing each json item in variable
						String uid = c.getString(TAG_UID);
						String name = c.getString(TAG_UNINAME);
			
						// creating new HashMap
						HashMap<String, String> map = new HashMap<String, String>();

						// adding each child node to HashMap key => value
						map.put(TAG_UID, uid);
						map.put(TAG_UNINAME, name);
						
						// adding HashList to ArrayList
						uniList.add(map);
						
						//Store Uni name into Array
						uniArray.add(c.getString(TAG_UNINAME));
						
					}
					
				} 
				else 
				{

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			//Get Courses
			
			List<NameValuePair> params1 = new ArrayList<NameValuePair>();
			JSONObject json1 = jParser.makeHttpRequest(url_all_courses, "GET", params1);
			
			// Check your log cat for JSON reponse
			Log.d("All Courses: ", json1.toString());
			
			// Course auto-complete data
			try {
				// Checking for SUCCESS TAG
				int success = json1.getInt(TAG_SUCCESS);
				
				if (success == 1) {
					
					// Courses found
					// Getting Array of Courses
					courses = json1.getJSONArray(TAG_COURSES);
					courseArray = new ArrayList<String>();
					tempArray = new ArrayList<String>();
					
					nusArray = new ArrayList<String>();
					ntuArray = new ArrayList<String>();
					smuArray = new ArrayList<String>();
					sitArray = new ArrayList<String>();
					
					// looping through All Courses and seperating into Universities
					for (int i = 0; i < courses.length(); i++) {
						JSONObject c = courses.getJSONObject(i);

						if(c.getString("uniName").equals("NUS"))
						{
							nusArray.add(c.getString("courseName"));
						}
						else if (c.getString("uniName").equals("NTU"))
						{
							ntuArray.add(c.getString("courseName"));
						}
						else if (c.getString("uniName").equals("SMU"))
						{
							smuArray.add(c.getString("courseName"));
						}
						else if (c.getString("uniName").equals("SIT"))
						{
							sitArray.add(c.getString("courseName"));
						}
						
						courseArray.add(c.getString(TAG_COURSENAME));
												
					}
					
					tempArray.addAll(nusArray);
					tempArray.addAll(ntuArray);
					tempArray.addAll(smuArray);
					tempArray.addAll(sitArray);
			
				} 
				else 
				{

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */

					// Populate Spinners
					
					spAdapter1 = new ArrayAdapter<String> (getActivity(),  android.R.layout.simple_dropdown_item_1line,
							uniArray);
					spAdapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
					
					
					sp1.setAdapter(spAdapter1);
					
					spAdapter1.notifyDataSetChanged();
					
					
					spAdapter2 = new ArrayAdapter<String> (getActivity(),  android.R.layout.simple_dropdown_item_1line,
							uniArray);
					spAdapter2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
					sp2.setAdapter(spAdapter2);
					
					// Populate Autocomplete
					acAdapter1 = new ArrayAdapter<String>(getActivity() ,android.R.layout.simple_dropdown_item_1line, tempArray);
					acAdapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
					ac1.setThreshold(1);
					ac1.setAdapter(acAdapter1);
					
					acAdapter2 = new ArrayAdapter<String>(getActivity() ,android.R.layout.simple_dropdown_item_1line, tempArray);
					acAdapter2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
					ac2.setThreshold(1);
					ac2.setAdapter(acAdapter2);
					
				}
			});

		}

	}
	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        setUserVisibleHint(true);
    }
}
